package com.px.user.config;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.core.Authentication;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.security.Principal;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.Optional;

@Configuration
@EnableSwagger2
@Profile({"dev", "alone", "docker-user", "test"})
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .ignoredParameterTypes(Authentication.class, Principal.class)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.px.user"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo())
                .securitySchemes(Collections.singletonList(
                        new ApiKey("token", "Authorization", "header")))
                .useDefaultResponseMessages(false)
                .genericModelSubstitutes(Optional.class)
                .directModelSubstitute(Timestamp.class, Long.class);
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("video")
                .termsOfServiceUrl("any.com")
                .contact(new Contact("any", "http://any.any", "any@any.com"))
                .version("v1.0")
                .build();
    }
}

@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
@SuppressWarnings("deprecation")
class ResourceHandlerConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html**")
                .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}